// Learn JavaScript:
//  - Created by zhanghejun
// 	- creation time ：  2022-01-3
//  - 

const verify = require('../../Utils/verify');
cc.Class({
    extends: cc.Component,

    properties: {
        ui_accont:cc.EditBox,
        ui_password:cc.EditBox,
        ui_Toggle:cc.Toggle
    },


    onLoad () {
        if (cc.sys.localStorage.getItem('user_account') && cc.sys.localStorage.getItem('user_password')){
            this.ui_accont.string = cc.sys.localStorage.getItem('user_account');
            this.ui_password.string = cc.sys.localStorage.getItem('user_password');
        }
    },


    // update (dt) {},
    onclick(event,customEventData){
        Global.AudioManager.playSound();

        if(customEventData =='close'){
            this.node.removeFromParent();
        }else if(customEventData == 'account_register'){
            this.removeLayer();
            Global.LayerManager.create('prefabs/login/RegisterLayer','RegisterLayer');
        }else if(customEventData == 'account_login'){
            this.account_login()
        }
    },
    account_login(){
        let _this = this;
        if (!this.ui_accont.string || !verify.enOrNum(this.ui_accont.string)){
            createTips('账号有误,请重新输入',Global.Code.FAIL);
            return;
        };
        if (!this.ui_password.string){
            createTips('请输入密码',Global.Code.FAIL);
            return;
        };
        
        showWaiting(true);
        Global.HttpApi.login({account:this.ui_accont.string,password:this.ui_password.string},function(result){
            Global.NoticeManager.emitMessage('UpdateToken',result.data.userinfo.token);
            Global.NoticeManager.emitMessage('UpdateUserInfoPush',result.data.userinfo.token);
            
            if (_this.ui_Toggle.isChecked){
                cc.sys.localStorage.setItem('user_account',_this.ui_accont.string)
                cc.sys.localStorage.setItem('user_password',_this.ui_password.string)
            }else{
                cc.sys.localStorage.removeItem('user_account')
                cc.sys.localStorage.removeItem('user_password')
            }

            createTips(result.msg,Global.Code.SUCCESS);
            setTimeout(function(){
                cc.director.loadScene("hallScence");
            },1000); 
        },function(res){
            showWaiting();
            createTips(res.msg,Global.Code.FAIL);
        });
    },
    removeLayer(){
        Global.LayerManager.remove('AccountLayer');
    }
});
